<template>
  <div
    ref="erpSearchTree"
    class="erp-search-tree"
    :style="{
      width: width + 'px',
      height: computedHeight,
      marginRight: position === 'left' ? '10px' : '0',
      marginLeft: position === 'right' ? '10px' : '0'
    }"
  >
    <el-scrollbar
      style="height: 100%"
    >
      <div
        class="tree-box"
      >
        <el-input
          v-model="filterText"
          style="width:100%;"
          :placeholder="searchPlaceholder"
          clearable
          @keyup.native="searchEvent"
          @clear="handleClear"
        >
          <template #append>
            <el-button
              type="primary"
              @click="handleClickAll"
            >
              所有
            </el-button>
          </template>
        </el-input>
        <erp-table
          ref="tree"
          v-loading="loading"
          :element-loading-text="$store.state.loading.text"
          :element-loading-spinner="$store.state.loading.spinner"
          :element-loading-background="$store.state.loading.background"
          class="tree-line"
          :is-tree="true"
          :data="tableData"
          :show-header="false"
          :list-permission="true"
          :tree-config="treeConfig"
          @current-change="handleCurrentChange"
        >
          <vxe-table-column
            :field="labelKey"
            tree-node
          />
        </erp-table>
        <!--                <el-tree-->
        <!--                    v-loading="loading"-->
        <!--                    element-loading-text="正在加载中..."-->
        <!--                    element-loading-spinner="el-icon-loading"-->
        <!--                    class="tree-line"-->
        <!--                    ref="tree"-->
        <!--                    v-bind="props"-->
        <!--                    :data="initData"-->
        <!--                    :filter-node-method="filterNode"-->
        <!--                    @node-click="handleNodeClick"-->
        <!--                >-->
        <!--                </el-tree>-->
      </div>
    </el-scrollbar>
  </div>
</template>

<script>
import Vue from 'vue';
import {base as request} from '@/request';
import {Tree} from "element-ui";
import ErpTable from '@/components/erp/ErpPageTable/ErpTable';
import XEUtils from 'xe-utils';
import {VXETable} from 'vxe-table';
import {toString} from '@/utils';
Vue.use(Tree);
/**
 * 表格增加树形搜索
 */
export default {
  name: "ErpSearchTree",
  components: {ErpTable},
  props: {
    /**
     * 树形搜索的宽度
     * @public
     */
    width: {
      type: Number,
      default: 150
    },
    /**
     * 选项，[参考](../eg/ErpListPage.html#options)
     * @public
     */
    props: {
      type: Object,
      default: () => {}
    },
    /**
     * 树形搜索位置，可选(left:左边,right:右边)
     * @public
     */
    position: {
      type: String,
      default: 'left'
    },
    /**
     * 树形搜索内部输入框的空白占位符
     * @public
     */
    searchPlaceholder: {
      type: String,
      default: '请输入关键字'
    },
    /**
     * 树形搜索在查询表单中的字段名
     * @public
     */
    searchKey: {
      type: String,
      required: true
    },
    /**
     * 远程请求树时配置请求api
     * @public
     */
    apiList: {
      type: Object,
      default () {
        return {
          list: {
            url: "",
          }
        };
      }
    },
    /**
     * 若未配置远程请求树，则设置树列表的数据
     * @public
     */
    data: {
      type: Array,
      default () {
        return [];
      }
    }
  },
  data () {
    return {
      loading: false,
      initData: [],
      tableData: [],
      filterText: null,
      computedHeight: 0,
    };
  },
  computed: {
    primaryKey () {
      return this.props && this.props.nodeKey ? this.props.nodeKey : 'id';
    },
    labelKey () {
      return this.props && this.props.props && this.props.props.label ? this.props.props.label : 'label';
    },
    childrenKey () {
      return this.props && this.props.treeConfig && this.props.treeConfig.children ? this.props.treeConfig.children : 'children';
    },
    computedData () {
      return this.data;
    },
    listApi () {
      return this.apiList && this.apiList.list ? this.apiList.list : null;
    },
    treeConfig () {
      let defaultConfig = {
        children: 'children',
        indent: 20,
        line: true,
        expandAll: true,
      };
      return Object.assign(defaultConfig, this.props && this.props.treeConfig ? this.props.treeConfig : {});
    },
    expandAll () {
      return this.treeConfig.expandAll;
    }
  },
  watch: {
    filterText(val) {
      // this.handleSearch(val)
    },
    'apiList': {
      handler (apiList) {
        if (!(apiList && apiList.list && apiList.list.url)) {
          this.initData = this.data;
          this.tableData = this.data;
          this.fetchHeight();
        } else {
          this.getRemoteData();
        }
      },
      immediate: true
    },
  },
  created() {
  },
  methods: {
    /**
     * 获取搜索树的高度
     * @private
     */
    fetchHeight () {
      let h = 0;
      if (this.$refs.erpSearchTree) {
        h = this.$refs.erpSearchTree.parentNode.offsetHeight;
      }
      this.$nextTick(() => {
        this.computedHeight = h + 'px';
      });
    },
    /**
     * 过滤树节点
     * @param {string|number} value 输入的关键字
     * @param {array} data 树列表
     * @private
     */
    filterNode(value, data) {
      if (!value) return true;
      return data[this.labelKey].indexOf(value) !== -1;
    },
    handleNodeClick (data, node, d) {
      let obj = {};
      obj[this.searchKey] = data[this.primaryKey];
      this.$emit('search', obj);
    },
    handleClear () {
      this.tableData = this.initData;
      this.$nextTick(() => {
        this.$refs.tree.$refs.erpTable.setAllTreeExpand(this.expandAll);
      });
    },
    /**
     * 获取所有
     * @public
     */
    handleClickAll () {
      this.filterText = null;
      let obj = {};
      let row = null;
      obj[this.searchKey] = null;
      this.$emit('search', {obj,row});
      this.$nextTick(() => {
        this.$refs.tree.$refs.erpTable.setAllTreeExpand(this.expandAll);
        this.$refs.tree.$refs.erpTable.clearCurrentRow();
      });
    },
    /**
     * 获取远程树
     * @private
     */
    getRemoteData () {
      let api = this.listApi;
      let url = api.url || '';
      let responseData = api.response || 'return response.list';
      let type = 'post';
      let requestMethod = request[type];
      if (url) {
        this.loading = true;
        requestMethod(url, api.query)
          .then(res => {
            const response = res.data;
            let initData = [];
            try{
              initData = new Function('response', responseData)(response);
            }catch (e) {
              initData = response.list;
              console.log('----远程获取筛选树----');
              console.log(e);
            }
            this.initData = initData;
            this.tableData = initData;
            this.fetchHeight();
          })
          .finally(() => {
            this.loading = false;
          });
      }
    },
    /**
     * 创建一个防反跳策略函数，调用频率间隔 500 毫秒
     * @public
     */
    searchEvent: XEUtils.debounce(function () {
      this.handleSearch();
    }, 500, { leading: false, trailing: true }),
    /**
     * 搜索树
     * @private
     */
    handleSearch () {
      let filterName = toString(this.filterText);
      if (filterName) {
        let options = { children: this.childrenKey };
        let searchProps = [this.labelKey];
        this.tableData = XEUtils.searchTree(this.initData, item => searchProps.some(key => toString(item[key]).indexOf(filterName) > -1), options);
        // 搜索之后默认展开所有子节点
        this.$nextTick(() => {
          this.$refs.tree.$refs.erpTable.setAllTreeExpand(this.expandAll);
        });
      } else {
        this.handleClear();
      }
    },
    /**
     * 点击树的某一行，触发搜索
     * @private
     * @param row
     */
    handleCurrentChange ({row}) {
      // console.log(row)
      let obj = {};
      obj[this.searchKey] = row[this.primaryKey];
      this.$emit('search', obj);
      this.$bus.$emit('searchId',row)
    }
  }
};
</script>

<style lang="scss" scoped>
    $fontSize: var(--font-size);
    .erp-search-tree{
        box-sizing: border-box;
        background-color: #fff;
        box-shadow: 0px 0px 10px 0px rgba(5, 5, 5, 0.1);
        overflow-y: auto;
        padding: 15px;
        .tree-box{
        }
        .tree-line{
           margin-top: 8px;
        }

    }
    ::v-deep{
        .el-scrollbar{
            .el-scrollbar__warp{
                overflow-x: hidden;
                overflow-y: scroll;
            }
        }

    }


</style>
